%  This file is part of Erlywog.

%  Erlywog is free software: you can redistribute it and/or modify
%  it under the terms of the GNU General Public License as published by
%  the Free Software Foundation, either version 3 of the License, or
%  (at your option) any later version.

%  Erlywog is distributed in the hope that it will be useful,
%  but WITHOUT ANY WARRANTY; without even the implied warranty of
%  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%  GNU General Public License for more details.

%  You should have received a copy of the GNU General Public License
%  along with Erlywog.  If not, see <http://www.gnu.org/licenses/>.

%  Copyright Jasm Sison 2009

-module(blog_util).
-compile(export_all).

%% controller return tuples
phased_response (Ewcs, PhasedVars) ->
{
  response
  , [ {phased_vars, PhasedVars}
    , {body, Ewcs}
  ]
}.

ajax_escape (IoList) ->
%  phased_response(Ewcs, [{ajax, []}]). %% works, but suboptimal
%   {response, [{html, IoList_or_Json}]}. %% nice try, but broken, because fucker returns also subcomponents
  {response, [{html, IoList}]}.

%% view functions
make_commas (Length) ->
  lists:reverse([" "] ++ lists:duplicate(Length,",")).

insert_commas (S) ->
  lists:flatten(lists:zipwith(fun(A,B) -> [A,B] end, S, make_commas(length(S)))).

%% used to randomly shuffle stuff in a list
shuffle(List) ->
    %% Determine the log n portion then randomize the list.
    randomize(round(math:log(length(List)) + 0.5), List).

randomize(1, List) ->
    randomize(List);
randomize(T, List) ->
    lists:foldl(fun(_E, Acc) ->
                        randomize(Acc)
                end, randomize(List), lists:seq(1, (T - 1))).

randomize(List) ->
    D = lists:map(fun(A) ->
                          {random:uniform(), A}
                  end, List),
    {_, D1} = lists:unzip(lists:keysort(1, D)),
    D1.

